/*!
 * http response
 * Copyright(c) purenode
 * @author yangjian102621@gmail.com
 * MIT Licensed
 */

"use strict";

/**
 * 初始化模块依赖
 */
var url = require("url");
var template = require("art-template");
var helpers = require("../template-helper");

function Response(res, app) {
	this.res = res;
	this.app = app;
}

//获取app对象
Response.prototype.getApp = function() {
	return this.app;
}

//获取原生http response对象
Response.prototype.getOriRes = function() {
	return this.res;
}

//继承http response对象的方法
Response.prototype.writeHead = function(code, headers) {
	this.res.writeHead(code, headers);
}

Response.prototype.write = function(str) {
	this.res.write(str);
}

Response.prototype.end = function() {
	this.res.end();
}

//解析模板
Response.prototype.display = function(view, data) {
	template.config('base', this.app.getConfig('tpl_path'));
	template.config("encoding", this.app.getConfig("tpl_encoding"));
	template.config("extname", this.app.getConfig("tpl_ext"));
	template.config("cache", this.app.getConfig("tpl_cache"));
	//配置模板引擎helper
	for ( var name in helpers ) {
		template.helper(name, helpers[name]);
	}
	
	//注册全局函数
	for ( var key in global ) {
		if ( key.indexOf('F_') == 0 ) {
			data[key] = global[key];
		}
	}
	var html = template(this.app.getModule()+"/views/"+view, data);
	this.res.write(html);
	this.res.end();
}

module.exports = Response;
